package com.study.userserviceprovider.biz.impl;

import com.study.exception.BizException;
import com.study.exception.ValidException;
import com.study.userserviceprovider.biz.AbstarctLogin;
import com.study.userserviceprovider.dto.AuthLoginDto;
import com.study.userserviceprovider.enums.LoginTypeEnum;
import com.study.userserviceprovider.mapper.entity.TbMember;
import com.study.userserviceprovider.mapper.entity.TbMemberExample;
import com.study.userserviceprovider.mapper.persistence.TbMemberMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.List;

;

/**
 * @description：用户密码登录处理
 * @author：李军荣
 * @date: 2020/12/28 11:14
 */
@Slf4j
@Service
public class NormalLoginProcessor extends AbstarctLogin{

    @Autowired
    private TbMemberMapper tbMemberMapper;

    @Override
    protected int getLoginType() {
        return LoginTypeEnum.NORMAL.getCode();
    }

    @Override
    protected boolean validate(AuthLoginDto authLoginDto) {
        if(StringUtils.isEmpty(authLoginDto.getUserName()) || StringUtils.isEmpty(authLoginDto.getPassword())){
            throw new ValidException("账号密码不能为空 ");
        }
        return true;
    }

    @Override
    protected TbMember doProcessor(AuthLoginDto authLoginDto) {
        log.info("begin NormalLoginProcessor doProcessor"+authLoginDto);
        TbMemberExample tbMemberExample=new TbMemberExample();
        tbMemberExample.createCriteria().andStateEqualTo(1).andUsernameEqualTo(authLoginDto.getUserName());
        List<TbMember> members = tbMemberMapper.selectByExample(tbMemberExample);
        if(members==null||members.size()==0){
            throw new BizException("用户名或者密码错误");
        }
        if(!DigestUtils.md5DigestAsHex(authLoginDto.getPassword().getBytes()).equals(members.get(0).getPassword())){
            throw new BizException("用户名或者密码错误");
        }
        return members.get(0);
    }
}
